﻿// See https://aka.ms/new-console-template for more information
using DynamicExpresso;

Console.WriteLine("========表达式树拼接=======");
var interpreter = new Interpreter();

{
    //计算数学表达式：
    var result = interpreter.Eval("8 / 2 + 2");
    //Console.WriteLine(result);
}
{
    // LINQ 查询生成委托和 lambda 表达式
    var prices = new[] { 5, 8, 6, 2 };
    var whereFunction = interpreter.ParseAsDelegate<Func<int, bool>>("arg > 5");
    var count = prices.Where(whereFunction).Count();
    //Console.WriteLine(count);
}
{
    double result = interpreter.Eval<double>("Math.Pow(x, y) + 5",
                        new Parameter("x", typeof(double), 10),
                        new Parameter("y", typeof(double), 2));
    //Console.WriteLine(result);
}
{
    //表达式拼接
    var customers = new List<Customer> {
        new Customer() { Name = "David", Age = 31, Gender = 'M' },
        new Customer() { Name = "Mary", Age = 29, Gender = 'F' },
        new Customer() { Name = "Jack", Age = 2, Gender = 'M' },
        new Customer() { Name = "Marta", Age = 1, Gender = 'F' },
        new Customer() { Name = "Moses", Age = 120, Gender = 'M' },
    };
    string whereExpression = $"Customer.Age > 18 && Customer.Gender == 'F' && Customer.Name == \"Mary\" ";
    Console.WriteLine(whereExpression);
    ExpressionCalculate(customers);

    //计算数据结果
    void ExpressionCalculate<T>(List<T> datas)
    {
        Func<T, bool> dynamicWhere = interpreter.ParseAsDelegate<Func<T, bool>>(whereExpression, "Customer");
        var result = datas.Where(dynamicWhere).Count();
        Console.WriteLine($"查询结果:{result}");
    }
    Console.WriteLine("========表达式树拼接=======");
}

class Customer
{
    public string Name { get; set; }
    public int Age { get; set; }
    public char Gender { get; set; }
}